import { defineStore } from 'pinia'
import userApi from '@/api/user'
import type { loginParamsData, UserInfoDate } from '@/api/user'
import { allAsyncRoutes, anyRoute, staticRoutes } from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router'
import router from '@/router'
import cloneDeep from "lodash/cloneDeep";

//封装异步动态函数
function filterUserAsyncRoutes(
  allAsyncRoutes: RouteRecordRaw[],
  routeNames: string[]
) {
  let result = allAsyncRoutes.filter((item) => {
    if (routeNames.includes(item.name as string)) {
      // 考虑子路由的过滤
      if (item.children && item.children.length) {
        item.children = filterUserAsyncRoutes(item.children, routeNames);
      }
      return true;
    }
  });
  return result;
}

// 封装动态添加路由
function addRoutes(userAsyncRoutes: RouteRecordRaw[]) {
  userAsyncRoutes.forEach((item) => {
    router.addRoute(item);
  });
}

//封装重置路由
function resetRoute(){
  let oldRoutes=router.getRoutes()
  oldRoutes.forEach((item)=>{
    router.removeRoute(item.name as string)
  })
  addRoutes(staticRoutes)
}

interface UserInfoStateData {
  token: string
  userInfo: UserInfoDate
  menuRoutes: RouteRecordRaw[]
}

export const useUserInfoStore = defineStore('userInfo', {
  state(): UserInfoStateData {
    return {
      // token: '',//不考虑自动登录
      token: localStorage.getItem('token_key') || '',
      userInfo: {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: '',
      },
      menuRoutes: staticRoutes,
    }
  },
  actions: {
    async login(loginParams: loginParamsData) {
      try {
        const result = await userApi.userLogin(loginParams)
        this.token = result.token
        localStorage.setItem('token_key', result.token)
        return 'ok'
      } catch (error) {
        return Promise.reject('登录失败')
      }
    },
    async getUserInfo() {
      try {
        const result = await userApi.getUserInfo()
        this.userInfo = result

        let userAsyncRoutes = filterUserAsyncRoutes(
          cloneDeep(allAsyncRoutes),
          result.routes
        )

        addRoutes(userAsyncRoutes.concat(anyRoute))
        this.menuRoutes = staticRoutes.concat(userAsyncRoutes, anyRoute)

        return 'ok'
      } catch (error) {
        return Promise.reject('获取用户信息失败')
      }
    },
    reset() {
      ;(this.token = ''),
        localStorage.removeItem('token_key'),
        (this.userInfo = {
          routes: [],
          buttons: [],
          roles: [],
          name: '',
          avatar: '',
        })
    },
    async logout() {
      try {
        await userApi.userLogout()
        this.reset()
        //重置路由
        //解决普通用户没有对应菜单 地址栏输入却能路由跳转bug
        resetRoute()
        return 'ok'
      } catch (error) {
        return Promise.reject('退出登录失败')
      }
    },
  },
  getters: {},
})
